package com.vote.csdn.controller;

import com.vote.csdn.service.CsdnService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author: larry.xiang
 * @description:  页面控制器
 */
@Controller
@RequestMapping
public class CsdnController {


    @Resource
    CsdnService csdnService;

    /**
     * 展示页面
     * @param request
     * @return
     */
    @RequestMapping("blockchain")
    public String index(HttpServletRequest request){
        csdnService.getCsdnContent();
        request.setAttribute("lst",csdnService.csdnList);
        request.setAttribute("sum",csdnService.sum);
        request.setAttribute("userName",csdnService.userName);
        return "2020csdn";
    }


    /**
     * 抽奖接口
     * @return
     */
    @RequestMapping("lottery")
    @ResponseBody
    public String lottery(){
        String id = csdnService.handleLottery();
        return id;
    }


    /**
     * 定时触发智能合约抽奖,并自动公布结果
     *      这里是结合宝塔的定时器进行时间的调度，不单独在项目中进行时间调度工作。注意我们这里的url为bclottery_wa7ndmvt2，相当于加了一个密码
     * @return
     */
    @RequestMapping("bclottery_wa7ndmvt2")
    @ResponseBody
    public void bcLottery(HttpServletRequest request){
        // 先判断是否进入top100
      if(csdnService.getRanking()) {
          // 触发智能合约抽奖
          String res = csdnService.handle("request");
          if (res.contains("transactionHash")) {
              // 获取合约结果
              res = csdnService.handle("get");
              // 拿到结果进行对比后进行页面公布
              res = csdnService.getUserNameById(Integer.parseInt(res));
              csdnService.userName = "中奖用户为："+res;
          }
      }else {
          csdnService.userName="博主未进top100,没有触发抽奖合约,本次抽奖失效！";
        }
    }
}
